// 保存图片
let settingWritePhotosAlbum = false

function saveImageToPhotosAlbum(filePath: string, callback?: () => void) {
  uni.saveImageToPhotosAlbum({
    filePath,
    success: () => {
      uni.hideLoading()
      callback && callback()
      uni.showToast({
        title: '保存成功',
      })
    },
    fail(e) {
      uni.hideLoading()
      if (e.errMsg !== 'writeFile:ok' && e.errMsg !== 'saveImageToPhotosAlbum:fail cancel') {
        uni.showToast({
          title: `下载失败，错误原因：${e.errMsg}`,
          icon: 'none',
        })
      }
      else {
        uni.showToast({
          title: '已取消下载',
          icon: 'none',
        })
      }
    },
  })
}

export function saveImg(url: string, name = 'qrcodeImg', callback?: () => void) {
  // 获取文件管理器对象
  const fs = uni.getFileSystemManager()
  // 文件保存路径
  // @ts-ignore
  const Imgpath = `${wx.env.USER_DATA_PATH}/${name}.png`
  // base64图片文件
  const imageSrc = url.replace(/^data:image\/\w+;base64,/, '')

  // 写入本地文件
  fs.writeFile({
    filePath: Imgpath,
    data: imageSrc,
    encoding: 'base64',
    success(res) {
      if (url) {
        if (settingWritePhotosAlbum) {
          uni.getSetting({
            success: (res: any) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                saveImageToPhotosAlbum(Imgpath, callback)
              }
              else {
                uni.showModal({
                  title: '提示',
                  content: '请先在设置页面打开“保存相册”使用权限',
                  confirmText: '去设置',
                  cancelText: '算了',
                  success: (data: any) => {
                    if (data.confirm) {
                      uni.openSetting()
                    }
                  },
                })
              }
            },
          })
        }
        else {
          settingWritePhotosAlbum = true
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              saveImageToPhotosAlbum(Imgpath, callback)
            },
          })
        }
      }
      else {
        uni.showToast({
          title: '未找到图片',
          icon: 'none',
        })
      }
    },
  })
}
